<template>
  <Top-Page>
    <cu-custom bgColor="bg-gradual-green" :isBack="true">
      <template #backText></template>
      <template #content>群成员</template>
      <template #right v-if="['2', '3'].includes(query.type)">
        <view class="f-14 ml-10 mr-10" @tap="calling()">发起</view>
      </template>
    </cu-custom>
    <!-- :style="[{ top: CustomBar + 'px' }]" -->
    <view class="cu-bar bg-white search fixed">
      <view class="search-form round">
        <text class="cuIcon-search"></text>
        <input type="text" v-model="keywords" placeholder="输入搜索的关键词" confirm-type="search" />
      </view>
    </view>
    <view class="cu-list-wrap">
      <view>
        <checkbox-group class="cu-list menu-avatar" :key="'message-list'">
          <view class="cu-item-1" v-for="item in userList">
            <view class="cu-item-1__unit">
              <view
                :class="[appSetting.circleAvatar ? 'round' : 'radius', 'cu-avatar', 'lg']"
                :style="'background-image:url(' + item.userInfo.avatar + ');'"
                @tap="openChatDetail(item)"
              ></view>
              <view class="content">
                <view class="text-grey">
                  <view class="text-cut">{{ item.userInfo.displayName }}</view>
                  <view v-if="item.role < 3" class="cu-tag round sm" :class="item.role == 1 ? 'bg-red' : 'bg-orange'">
                    {{ item.role == 1 ? "群主" : item.role == 2 ? "管理员" : "" }}
                  </view>
                  <view v-if="item.user_id == userInfo.user_id" class="cu-tag round sm">我</view>
                </view>
              </view>
            </view>
            <view class="cu-item-1__unit">
              <view class="action" @tap="openModel(item)">
                <view class="text-grey text-sm">
                  <text class="cuIcon-more f-24"></text>
                </view>
              </view>
              <checkbox
                v-if="['2', '3'].includes(query.type) && item.user_id != userInfo.user_id"
                class="collect-checkbox"
                :checked="item.checked"
                @click="item.checked = !item.checked"
              />
            </view>
          </view>
        </checkbox-group>
        <Empty v-if="!userList.length" noDatatext="未搜索到数据" textcolor="#999"></Empty>
      </view>
    </view>
    <view class="cu-modal bottom-modal" :class="modelName == 'userOpt' ? 'show' : ''">
      <view class="cu-dialog">
        <view class="manage-content">
          <view class="cu-list menu bg-white">
            <view class="cu-item" v-if="curUser">
              <view class="content im-flex im-justify-content-center im-align-items-center">
                <view class="cu-avatar round sm" :style="'background-image:url(' + curUser.avatar + ');'"></view>
                <view class="text-cut ml-5">{{ curUser.realname }}</view>
                <view v-if="curUser.role == 2" class="cu-tag round sm bg-orange">管理员</view>
              </view>
            </view>
            <view class="cu-item" @tap="changeOwner()" v-if="isAdmin">
              <view class="content padding-tb-sm">
                <text class="c-orange">转让管理权限</text>
              </view>
            </view>
            <view class="cu-item" @tap="setManage()" v-if="isAdmin">
              <view class="content padding-tb-sm">
                <text>{{ curUser.role == 2 ? "取消管理员" : "设为管理员" }}</text>
              </view>
            </view>
            <view class="cu-item" @tap="setOpenSpeech(0)" v-if="isAdmin">
              <view class="content padding-tb-sm">
                <text>
                  {{ curUser.open_speech == 2 ? "取消禁言" : "禁言" }}
                </text>
              </view>
            </view>
            <view class="cu-item" @tap="setOpenSpeech(1)" v-if="isAdmin">
              <view class="content padding-tb-sm">
                <text>
                  {{ curUser.open_speech == 1 ? "禁止发言" : "可发言" }}
                </text>
                <text class="explain">(群禁言时单独管理)</text>
              </view>
            </view>
            <view class="cu-item" @tap="removeUser()">
              <view class="content padding-tb-sm">
                <text>移出群聊</text>
              </view>
            </view>
            <view class="parting-line-5"></view>
            <view class="cu-item" @tap="modelName = ''">
              <view class="content padding-tb-sm">
                <text class="c-red">取消</text>
              </view>
            </view>
          </view>
        </view>
      </view>
    </view>
  </Top-Page>
</template>
<script>
import { useMsgStore } from "@/store/message";
import pinia from "@/store/index";
const msgStore = useMsgStore(pinia);

import { useloginStore } from "@/store/login";
const userStore = useloginStore(pinia);
export default {
  data() {
    return {
      // banned: 0, // 0取消禁言 1禁言
      query: {},
      openSpeech: 1,
      speech: 1,
      keywords: "",
      group_id: "",
      modelName: "",
      userList: [],
      allUser: [],
      isAdmin: false,
      isManage: false,
      isAuth: false,
      userInfo: uni.getStorageSync("userInfo"),
      appSetting: userStore.appSetting,
      curUser: {}, //选中的用户
    };
  },
  watch: {
    keywords(val) {
      if (val == "") {
        // this.userList = this.allUser;
        this.userList.length = 0;
        this.userList.push(...this.allUser);
      } else {
        this.search();
      }
    },
  },
  onLoad(options) {
    this.group_id = options.group_id ? options.group_id : "";
    this.getGroupuserlist();
    Object.assign(this.query, options);
  },
  methods: {
    //发起群通话
    calling() {
      const checkedList = this.userList.filter((item) => item.checked);
      const checkedUsers = checkedList.map((item) => item.userInfo);
      const usersID = checkedList.map((item) => item.user_id);

      if (!usersID.length) {
        uni.showToast({
          title: "请选择至少一名群友",
          icon: "none",
        });

        return;
      }

      const { type, id, name, avatar, msg_id } = this.query;
      const isVideo = type == 2 ? 1 : 2;

      let path = "h5-call";
      // #ifdef APP
      path = "app-call";
      // #endif

      const url = `/pages/message/${path}?type=${isVideo}&msg_id=${msg_id}&status=call&id=${id}&name=${name}&avatar=${avatar}&userID=${this.userInfo.user_id}`;

      const memberList = checkedUsers.map((item) => {
        return {
          userID: item.id,
          nick: item.displayName,
          isAll: true,
          avatar: item.avatar,
        };
      });

      msgStore.changeMemberList(memberList);

      uni.redirectTo({
        url: url,
      });
    },
    getGroupuserlist() {
      // this.userList = [];
      this.userList.length = 0;
      this.$api.msgApi
        .groupUserList({
          group_id: this.group_id,
        })
        .then((res) => {
          const admin = res.data.filter((item) => item.role == 1 && item.userInfo.id == this.userInfo.user_id);
          if (admin.length) this.isAdmin = true;
          const manage = res.data.filter((item) => item.role == 2 && item.userInfo.id == this.userInfo.user_id);
          if (manage.length) this.manage = true;
          if (admin.length || manage.length) this.isAuth = true;
          const allUser = res.data;
          allUser.forEach((item) => {
            item.realname = item.userInfo.displayName;
            item.name_py = item.userInfo.name_py;
          });
          this.allUser.length = 0;
          this.allUser.push(...allUser);
          this.userList.length = 0;
          this.userList.push(...res.data);

          // this.allUser = allUser;
          // this.userList = res.data;
          this.$nextTick(() => {
            this.$forceUpdate();
            console.log("更新后的内容");
            console.log(this.userInfo, this.userList);
          });
        });
    },
    openModel(item) {
      item.realname = item.userInfo.displayName;
      item.avatar = item.userInfo.avatar;
      this.curUser = item;
      this.modelName = "userOpt";
    },

    //禁言
    setOpenSpeech(t) {
      const speech = t ? (this.curUser.open_speech != 1 ? 1 : 0) : this.curUser.open_speech != 2 ? 2 : 0;

      const data = {
        id: this.group_id,
        user_id: this.curUser.user_id,
        speech: speech,
      };

      this.$api.msgApi.setOpenSpeech(data).then((res) => {
        if (res.code == 0) {
          this.curUser.open_speech = speech;
          uni.showToast({
            title: `${res.msg}`,
            icon: "none",
          });
        }
      });
    },
    //禁止/取消 发言
    forbidSpeak() {
      const _banned = this.banned == 0 ? 1 : 0;
      //
      banned: _banned;
      this.$api.msgApi
        .setBanned({
          id: this.group_id,
          user_id: this.curUser.user_id,
        })
        .then((res) => {
          if (res.code == 0) {
            // this.getGroupuserlist();
            this.banned = _banned;
          }
          this.modelName = "";
        });
    },
    // 设置取消管理员
    setManage() {
      const role = this.curUser.role == 2 ? 3 : 2;
      this.$api.msgApi
        .setManager({
          id: this.group_id,
          user_id: this.curUser.user_id,
          role: role,
        })
        .then((res) => {
          if (res.code == 0) {
            this.getGroupuserlist();
          }
          this.modelName = "";
        });
    },
    // 移出成员
    removeUser() {
      this.modelName = "";
      uni.showModal({
        title: "确定要删除该成员吗?",
        success: (e) => {
          if (e.confirm) {
            this.$api.msgApi
              .removeUser({
                id: this.group_id,
                user_id: this.curUser.user_id,
              })
              .then((res) => {
                if (res.code == 0) {
                  this.getGroupuserlist();
                }
              });
          }
        },
      });
    },
    changeOwner() {
      this.modelName = "";
      uni.showModal({
        title: "确定将管理权限转移给该成员吗?",
        success: (e) => {
          if (e.confirm) {
            this.$api.msgApi
              .changeOwner({
                id: this.group_id,
                user_id: this.curUser.user_id,
              })
              .then((res) => {
                if (res.code == 0) {
                  uni.reLaunch({
                    url: "/pages/index/index",
                  });
                }
              });
          }
        },
      });
    },
    search() {
      const allUser = JSON.parse(JSON.stringify(this.allUser));
      const userList = this.$util.searchObject(allUser, ["realname", "name_py"], this.keywords);
      this.userList.length = 0;
      this.userList.push(...userList);
    },
    openChatDetail(item) {
      uni.navigateTo({
        // url: '/pages/contacts/detail?id=' + item.user_id
        url: `/pages/contacts/detail?id=${item.user_id}&source=group&group_id=${this.group_id}`,
      });
      // if (userInfo.user_id == item.user_id) return;
      // let friend = msgStore.getContact(item.user_id);
      // let curContact = msgStore.getContact(this.group_id);
      // if (curContact.role < 3 || curContact.setting.profile == '1' || friend) {
      //   uni.navigateTo({
      //     // url: '/pages/contacts/detail?id=' + item.user_id
      //     url: `/pages/contacts/detail?id=${item.user_id}&source=group&group_id=${this.group_id}`
      //   });
      // } else {
      //   uni.showToast({
      //     title: '已开启用户隐私！',
      //     icon: 'none'
      //   });
      //   return false;
      // }
    },
  },
};
</script>
<style scoped lang="scss">
.cu-list-wrap {
  margin-top: calc(var(--amplified_base) * 104rpx);
}
.list-image {
  width: calc(var(--amplified_base) * 80rpx);
  height: calc(var(--amplified_base) * 80rpx);
  font-size: 0;
}

.cu-bar {
  top: calc(var(--amplified_base) * v-bing(CustomBars));
}

.explain {
  color: #999;
  font-size: 26rpx;
  margin-left: 10rpx;
}

.menu-avatar {
  background-color: #fff;
}
.cu-item-1 {
  display: flex;
  align-items: center;
  justify-content: space-between;
  padding: 20rpx;

  .cu-item-1__unit {
    display: flex;
    flex-direction: row;
    align-items: center;

    .text-grey {
      display: flex;
      flex-direction: row;
      align-items: center;

      .text-cut {
        margin: 0 20rpx;
      }
    }

    :deep .uni-checkbox-wrapper {
      margin-left: 20rpx;
    }
  }
}
</style>
